package com.simple.auth.service.impl;

import com.simple.auth.domain.vo.CaptchaVo;
import com.simple.auth.service.CaptchaService;
import com.simple.common.constant.CommonConstants;
import com.simple.common.exception.ServiceException;
import com.simple.framework.core.redis.RedisService;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description 验证码实现类
 * @Author xiaoke
 * @Date 2024/8/11 15:39
 * @Version 1.0
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {
    private final RedisService redisService;

    public CaptchaServiceImpl(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public CaptchaVo generated() { // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 60);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = "";
        try {
            result = String.valueOf(new Double(Double.parseDouble(captcha.text())).intValue());
        } catch (Exception e) {
            result = captcha.text();
        }
        String uuid = UUID.randomUUID().toString();
        setCaptchaCache(result, uuid);
        return CaptchaVo.builder()
                .img(captcha.toBase64())
                .key(uuid)
                .build();
    }

    @Override
    public boolean check(String key, String code) {
        String result = redisService.getCacheObject(CommonConstants.SMS_CODE_KEY + key);
        if (result == null) {
            throw new ServiceException("验证码不存在");
        }
        boolean equals = result.equals(code.toLowerCase());
        if (equals) {
            deleteCaptchaCache(key);
        }
        return equals;
    }

    /**
     * 设置验证码缓存
     *
     * @param result 验证码生成结果
     * @param uuid   key
     */
    private void setCaptchaCache(String result, String uuid) {
        redisService.setCacheObject(CommonConstants.SMS_CODE_KEY + uuid, result, 3L, TimeUnit.MINUTES);
    }

    /**
     * 删除验证码缓存
     *
     * @param key key
     */
    private void deleteCaptchaCache(String key) {
        redisService.deleteObject(CommonConstants.SMS_CODE_KEY + key);
    }
}
